package com.example.demo;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootDemo2Application.class)
public class MetaDataTest2 {

    @Test
    public void test() throws SQLException {
        Connection connection =
                DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test2?useSSL=false&serverTimezone=UTC",
                        "root", "123456");
        try {
            ;
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet rs = metaData.getPrimaryKeys("TEST2", null, "t_user1_1");

            List<MetaKeyInfo> metaKeyInfos = new ArrayList<>();
            while (rs.next()) {
                MetaKeyInfo keyInfo = new MetaKeyInfo();
                keyInfo.setName(rs.getString("PK_NAME"));
                keyInfo.setColumns(rs.getString("COLUMN_NAME"));
                keyInfo.setType("Primary");
                metaKeyInfos.add(keyInfo);
            }

            List<MetaKeyInfo> keyInfos = new ArrayList<>();
            Map<String, List<MetaKeyInfo>> collect = metaKeyInfos.stream().filter(t -> StringUtils.isNotEmpty(t.getName()) && StringUtils.isNotEmpty(t.getColumns())).collect(Collectors.groupingBy(MetaKeyInfo::getName));
            collect.keySet().stream().forEach(t -> {
                MetaKeyInfo keyInfo = new MetaKeyInfo();
                keyInfo.setName(t);
                keyInfo.setType("Primary");
                keyInfo.setColumns(String.join(",", collect.get(t).stream().map(MetaKeyInfo::getColumns).collect(Collectors.toList())));
                keyInfos.add(keyInfo);
            });
            log.info(keyInfos.toString());
        } finally {
            if (connection != null) {
                connection.close();
            }
        }

    }





}
